<template>
  <div>
    <PageWrapper class="list-basic" title="文件列表">
      <template #headerContent>
        <a-button type="primary" @click="handleAdd">上传文件</a-button>
        <a-button class="ml-4" @click="showDeleteConfirm('all')">删除全部</a-button>
      </template>
      <div :class="`list-basic__content`">
        <a-table
          :dataSource="list"
          size="middle"
          :scroll="{ x: 800 }"
          :columns="columns"
          :pagination="pagination"
          :loading="loading"
          :row-selection="{
            columnWidth: '40px',
            hideDefaultSelections: true,
            selectedRowKeys: selectedRowKeys,
            onSelect: onSelect,
            onSelectAll: onSelectAll,
          }"
          @change="onChange"
        >
          <template #title>
            <a-button
              type="primary"
              :disabled="selectedRowKeys.length === 0"
              @click="showDeleteConfirm('checkbox')"
              >批量删除</a-button
            >
            <a-button
              class="ml-4"
              type="primary"
              :disabled="selectedRowKeys.length === 0"
              @click="showMove('checkbox')"
              >批量移动</a-button
            >
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'url'">
              <div class="img-div">
                <div class="img-div-img">
                  <a-image v-if="isImage(record.url)" :width="80" :height="80" :src="record.url" />
                  <FileExcelTwoTone
                    v-else-if="isExcel(record.url)"
                    style="font-size: 50px"
                    two-tone-color="#0960bd"
                  />
                  <FileWordTwoTone
                    v-else-if="isWord(record.url)"
                    style="font-size: 50px"
                    two-tone-color="#0960bd"
                  />
                  <FileTwoTone v-else style="font-size: 50px" two-tone-color="#0960bd" />
                </div>
                <div class="img-div-in">
                  <p>{{ record.url || '' }}</p>
                  <a v-if="record.url" class="src-but" @click="copyHandle(record.url)">复制地址</a>
                </div>
              </div>
            </template>
            <template v-else-if="column.dataIndex === 'delete'">
              <a class="edit-but" @click="editHandle(record)">编辑</a>
              <a class="edit-but" @click="showMove('radio', record.id)">移动</a>
              <a class="edit-but" @click="showDeleteConfirm('radio', record.id)">删除</a>
            </template>
          </template>
        </a-table>
      </div>
    </PageWrapper>
    <a-modal v-model:open="uploadOpen" title="文件上传" :closable="false">
      <template #footer>
        <div class="uploadL-footer">
          <a-button key="back" @click="handleCancel">取消</a-button>
          <a-button key="submit" type="primary" :loading="uploadLoading" @click="handleUploadOk"
            >确认</a-button
          >
        </div>
      </template>
      <div class="upload-div"
        >文件名称：
        <div class="upload-div-in"
          ><a-input
            v-model:value="uploadForm.name"
            placeholder="请输入图片名称"
            :allowClear="true"
            :status="inputStatus"
            :maxlength="100"
            @input="inputStatus = ''" /></div
      ></div>
      <div class="upload-div"
        >文件上传：
        <div class="upload-div-in upload-img"
          ><ImageUpload
            ref="uploadRef"
            :accept="accept"
            :maxNumber="1"
            :maxSize="20"
            :value="editList"
            @change="handleChange"
            :api="uploadApi" /></div
      ></div>
    </a-modal>
    <!-- 移动分类弹窗 -->
    <a-modal v-model:open="moveOpen" title="移动分类" :closable="false">
      <template #footer>
        <div class="move-footer">
          <a-button key="back" @click="moveColse">取消</a-button>
          <a-button key="submit" type="primary" :loading="moveOpenLoading" @click="handleMove"
            >确认</a-button
          >
        </div>
      </template>
      <div class="pt-3 pb-3">
        <a-select
          v-model:value="moveSelectInfo.moveOneName"
          style="width: 228px"
          :field-names="{ label: 'name', value: 'id' }"
          :options="categoryList"
          @change="handleChangeParent"
        />
        <a-select
          class="ml-4"
          v-model:value="moveSelectInfo.moveTwoName"
          style="width: 228px"
          :field-names="{ label: 'name', value: 'id' }"
          :options="childCategoryList"
          :allowClear="true"
          placeholder="不选择默认一级分类下"
          @deselect="handleDeselect"
          @change="handleChangeTwo"
        />
      </div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, createVNode, onMounted } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { message, Modal } from 'ant-design-vue';
  import {
    ExclamationCircleOutlined,
    FileTwoTone,
    FileExcelTwoTone,
    FileWordTwoTone,
  } from '@ant-design/icons-vue';
  import { ImageUpload } from '@/components/Upload';
  import { uploadApi } from '@/api/sys/upload';
  import { useRoute } from 'vue-router';
  import {
    addImage,
    deleteByCategoryId,
    deleteById,
    getAllCategory,
    getCategoryId,
    updateImageCategory,
    updateImageInfo,
  } from '@/api/home/images';

  const route = useRoute();
  const categoryId = ref<any>('');
  const categoryOneId = ref(route.query?.categoryOneId || '');
  const categoryTwoId = ref(route.query?.categoryTwoId || '');
  const accept = ref<string[]>([
    'doc',
    'docx',
    'xlsx',
    'xls',
    'dwg',
    'hdm',
    'jpg',
    'jpeg',
    'png',
    'gif',
    'bmp',
    'webp',
    'svg',
  ]);

  // 上传弹窗信息
  const inputStatus = ref('');
  const modalType = ref('add');
  const uploadOpen = ref(false);
  const uploadLoading = ref(false);
  const editList = ref<string[]>([]);
  const uploadForm = ref({
    name: '',
    url: '',
  });
  // 分页器
  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    showSizeChanger: false,
    position: ['bottomCenter'],
    size: 'large',
  });
  // 表单是否加载中
  const loading = ref(true);

  // 图片上传回调
  const handleChange = (file: string[]) => {
    uploadForm.value.url = file[0];
  };
  // 上传弹窗确认事件
  const handleUploadOk = async () => {
    try {
      if (!uploadForm.value.name) {
        return (inputStatus.value = 'error');
      }
      if (!uploadForm.value.url) {
        return message.warning('请上传图片');
      }
      uploadLoading.value = true;
      if (modalType.value === 'add') {
        await addImageFun();
      } else if (modalType.value === 'edit') {
        await updateCategoryFun();
      }
    } catch (error) {
      uploadLoading.value = true;
      console.log(error);
    }
  };

  onMounted(async () => {
    categoryId.value = categoryTwoId.value || categoryOneId.value;
    await getList();
  });
  // 定义 ImageUpload 的类型
  type ImageUploadInstance = InstanceType<typeof ImageUpload>;
  // 关闭弹窗
  const uploadRef = ref<ImageUploadInstance | null>(null);
  const handleCancel = () => {
    if (uploadRef.value) {
      uploadRef.value?.removeAll();
    }
    uploadOpen.value = false;
    modalType.value = 'add';
    uploadForm.value = {
      name: '',
      url: '',
    };
    editList.value = [];
    imageEditId.value = '';
  };
  const imageEditId = ref('');
  const editHandle = (record: any) => {
    modalType.value = 'edit';
    uploadOpen.value = true;
    imageEditId.value = record.id;
    uploadForm.value = {
      name: record.name,
      url: record.url,
    };
    editList.value = [uploadForm.value.url];
  };
  const handleAdd = () => {
    uploadOpen.value = true;
    editList.value = [];
  };
  // 编辑
  const updateCategoryFun = async () => {
    try {
      await updateImageInfo({
        id: imageEditId.value,
        ...uploadForm.value,
      });
      uploadLoading.value = false;
      await handleCancel();
      message.success('编辑成功');
      await getList();
    } catch (error) {
      uploadLoading.value = false;
    }
  };
  // 新增
  const addImageFun = async () => {
    try {
      await addImage({
        categoryOneId: categoryOneId.value || '',
        categoryTwoId: categoryTwoId.value || '',
        ...uploadForm.value,
      });
      uploadLoading.value = false;
      await handleCancel();
      message.success('上传成功');
      await getList();
    } catch (error) {
      uploadLoading.value = false;
    }
  };

  type ItemType = {
    id: number | string;
    key: number | string;
    url: string;
    categoryOneId: number;
    categoryTwoId: number;
    name: string;
    createdTime: string | null; // 或者使用 Date 类型，依据需求
  };
  const list = ref<ItemType[]>([]);
  // 获取列表数据
  const getList = async () => {
    try {
      if (!categoryId.value) {
        loading.value = false;
        return message.warning('缺失分类id必要参数');
      }
      const { records, total } = await getCategoryId({
        pageNo: pagination.value.current,
        pageSize: pagination.value.pageSize,
        id: categoryId.value,
      });
      if ((!records || records.length === 0) && pagination.value.current !== 1) {
        pagination.value.current = 1;
        await getList();
        return;
      }
      list.value =
        records.map((item: { id: any }) => {
          return { key: item.id, ...item };
        }) || [];
      pagination.value.total = total || 0;
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  };
  // 文件删除
  const showDeleteConfirm = (type: string, id?: number) => {
    Modal.confirm({
      title: '提示',
      content: '是否确定删除?',
      icon: createVNode(ExclamationCircleOutlined),
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      async onOk() {
        console.log('OK', id);
        if (type === 'all') {
          await deleteByCategoryIdFun();
        } else {
          await deleteByIdFun(type, id);
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  // 全部删除
  const deleteByCategoryIdFun = async () => {
    try {
      await deleteByCategoryId({
        id: categoryId.value,
      });
      message.success('删除成功');
      pagination.value.current = 1;
      await getList();
    } catch (error) {
      console.log(error);
    }
  };
  // 批量删除或者单个删除
  const deleteByIdFun = async (type: string, id?: number) => {
    try {
      const idList = type === 'checkbox' ? selectedRowKeys.value : [id];
      await deleteById({
        idList,
      });
      if (type === 'checkbox') {
        selectedRowKeys.value = [];
      } else {
        selectedRowKeys.value = selectedRowKeys.value.filter((item) => item !== id);
      }
      message.success('删除成功');
      await getList();
    } catch (error) {
      console.log(error);
    }
  };

  // 已经选择的列表id
  const selectedRowKeys = ref<(string | number)[]>([]);

  interface SelectedItem {
    id: number | string; // 根据实际的 id 类型调整
  }
  const onSelect = (e: SelectedItem) => {
    if (selectedRowKeys.value.includes(e?.id)) {
      selectedRowKeys.value = selectedRowKeys.value.filter((item) => item !== e?.id);
    } else {
      selectedRowKeys.value.push(e?.id);
    }
  };
  const onSelectAll = (e: boolean) => {
    if (e) {
      selectedRowKeys.value = [...selectedRowKeys.value, ...list.value.map((item) => item.id)];
    } else {
      for (let i = 0; i < list.value.length; i++) {
        if (selectedRowKeys.value.includes(list.value[i].id)) {
          selectedRowKeys.value = selectedRowKeys.value.filter((item) => item !== list.value[i].id);
        }
      }
    }
  };
  const onChange = async (pag: { current: number }) => {
    pagination.value.current = pag?.current || 1;
    loading.value = true;
    await getList();
  };
  // 移动分类
  const moveOpenLoading = ref(false);
  const moveOpen = ref(false);
  const moveType = ref('');
  const moveRadioId = ref<(number | undefined | string)[]>([]);
  const categoryList = ref<any>();
  const childCategoryList = ref<any>();
  // 分类选中的id和名称
  const moveSelectInfo = ref({
    moveOneId: '',
    moveOneName: null,
    moveTwoId: '',
    moveTwoName: null,
  });
  const showMove = async (type: string, _id?: number) => {
    moveOpen.value = true;
    moveType.value = type;
    if (type === 'checkbox') {
      moveRadioId.value = selectedRowKeys.value;
    } else {
      moveRadioId.value = [_id] || [];
    }
    await getCategoryList();
  };
  const moveColse = () => {
    moveOpen.value = false;
    moveType.value = '';
  };
  const handleMove = async () => {
    try {
      console.log(moveSelectInfo.value, moveRadioId.value);
      moveOpenLoading.value = true;
      if (
        moveSelectInfo.value.moveOneId.toString() === categoryOneId.value.toString() &&
        moveSelectInfo.value.moveTwoId.toString() === categoryTwoId.value.toString()
      ) {
        moveOpenLoading.value = false;
        return message.warning('请选择要移动的分类位置');
      }
      await updateImageCategory({
        categoryOneId: moveSelectInfo.value?.moveOneId || '',
        categoryTwoId: moveSelectInfo.value?.moveTwoId || '',
        listId: moveRadioId.value,
      });
      message.success('移动成功');
      if (moveType.value === 'checkbox') {
        selectedRowKeys.value = [];
      } else {
        selectedRowKeys.value = selectedRowKeys.value.filter(
          (item) => !moveRadioId.value.includes(item),
        );
      }
      await moveColse();
      await getList();
      moveOpenLoading.value = false;
    } catch (error) {
      moveOpenLoading.value = false;
    }
  };
  // 获取分类列表
  const getCategoryList = async () => {
    try {
      const data = await getAllCategory();
      categoryList.value = data || [];
      data.forEach((item) => {
        if (item.id.toString() === categoryOneId.value.toString()) {
          moveSelectInfo.value.moveOneName = item.name;
          moveSelectInfo.value.moveOneId = item.id;
          childCategoryList.value = [...item.levelTowCategoryList] || [];
          item.levelTowCategoryList.forEach((child) => {
            if (child.id.toString() === categoryTwoId.value.toString()) {
              moveSelectInfo.value.moveTwoName = child.name;
              moveSelectInfo.value.moveTwoId = child.id;
            }
          });
        }
      });
    } catch (error) {
      console.log(error);
    }
  };
  // 一级分类切换
  const handleChangeParent = (e) => {
    handleDeselect();
    childCategoryList.value = categoryList.value.filter(
      (item) => item.id === e,
    )[0]?.levelTowCategoryList;
    moveSelectInfo.value.moveOneId = e;
    moveSelectInfo.value.moveOneName = categoryList.value.filter((item) => item.id === e)[0]?.name;
  };
  const handleChangeTwo = (e) => {
    moveSelectInfo.value.moveTwoId = e;
    moveSelectInfo.value.moveTwoName = childCategoryList.value.filter(
      (item) => item.id === e,
    )[0]?.name;
  };
  const handleDeselect = () => {
    moveSelectInfo.value.moveTwoId = '';
    moveSelectInfo.value.moveTwoName = null;
  };
  // 表头设置
  const columns = ref([
    {
      title: '图片',
      dataIndex: 'url',
      key: 'url',
      width: '50%',
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'delete',
      align: 'center',
      width: 140,
      fixed: 'right',
    },
  ]);
  // 复制图片地址
  const copyHandle = async (src: string) => {
    try {
      if (!src) {
        message.warning('图片地址为空');
      }
      const tempInput = document.createElement('input');
      tempInput.value = src;
      document.body.appendChild(tempInput);
      // 选择文本
      tempInput.select();
      tempInput.setSelectionRange(0, 99999); // 对于移动设备
      // 执行复制命令
      document.execCommand('copy');
      // 移除临时输入元素
      document.body.removeChild(tempInput);
      // await navigator.clipboard.writeText(src);
      message.success('复制成功');
    } catch (err) {
      message.error('复制失败');
    }
  };
  const isImage = (url) => {
    return /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i.test(url);
  };
  const isWord = (url) => {
    return /\.(doc|docx)$/i.test(url);
  };

  const isExcel = (url) => {
    return /\.(xlsx|xls)$/i.test(url);
  };
</script>
<style lang="less" scoped>
  .edit-but {
    padding: 0 5px;
  }

  .move-footer {
    display: flex;
    justify-content: center;
  }

  .uploadL-footer {
    display: flex;
    justify-content: flex-start;
    padding-left: 70px;
  }

  .upload-div {
    display: flex;
    margin-top: 20px;

    .upload-img {
      min-height: 110px;
    }

    &-in {
      flex: 1;
    }
  }

  .img-div {
    display: flex;
    align-items: center;

    &-img {
      width: 80px;
    }

    &-in {
      flex: 1;
      padding-left: 10px;

      p {
        margin-bottom: 10px;
        word-break: break-all;
      }

      .src-but {
        cursor: pointer;
      }

      .src-but:hover {
        color: #1890ff;
      }
    }
  }

  :deep(.ant-page-header) {
    padding: 15px 24px;
  }

  .list-basic {
    &__content {
      padding: 10px 20px;
      background-color: @component-background;
    }
  }
</style>
